`

number to the ip variable. After each iteration, we use echo to

write the IP address to a dedicated file on disk, 172-16-10-hosts.txt.

#!/bin/bash

# generate IP addresses from a given range

for ip in $(seq 1 254); do

echo "172.16.10.${ip}" >> 172-16-10-hosts.txt

done

Listing 4-1

Using a for loop to create a list of IP addresses with the seq command

You can run this code directly from the command line or save it

in a script and then run it. The generated file should look like the

following:

$ cat 172-16-10-hosts.txt

172.16.10.1

172.16.10.2

172.16.10.3

172.16.10.4

172.16.10.5

--snip

Before moving on, let’s consider two other ways to accomplish

the same task.

The echo and Brace Expansion Approach

As in most cases, you can achieve the same task in bash using

multiple programming approaches. We can generate the IP address

list using a simple echo command, without running any loops. In

Listing 4-2, we use echo with brace expansion to generate the

strings.

$ echo 10.1.0.{1..254}

10.1.0.1 10.1.0.2 10.1.0.3 10.1.0.4 --snip--

Listing 4-2

Performing brace expansion with echo

Youll notice that this command outputs a list of IP addresses on

a single line, separated by spaces. This isn’t ideal, as what we really

want is each IP address on a separate line. In Listing 4-3, we use

sed to replace spaces with new line characters (\n).

$ echo 10.1.0.{1..254} | sed 's/ /\n/g'

10.1.0.1

10.1.0.2

Black Hat Bash (Early Access) © 2023 by Dolev Farhi and Nick Aleks